<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use Exception;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 微信商家转账接口调用示例
     */

    public function transfer()
    {
        $money = 1;
        $appid='wxc54a4da93113e17c';
        $openid='o3rhb1yNbuprhsW_LPWRWSMKo5Bw';
        $trade_no=date('YmdHis');


        $infos=[["info_type"=>"岗位类型", "info_content"=>"推广员"],["info_type"=>"报酬说明", "info_content"=>"佣金返利"]];
        $post_data = [
            "appid" => $appid,//appid
            "out_bill_no"=>'test'.date('YmdHis'),
            "transfer_scene_id"=>'1005',
            "openid" => $openid,
            "transfer_amount"=>100,
            "transfer_remark"=>'佣金报酬',
            "transfer_scene_report_infos" => $infos,
        ];
        $url = 'https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills';
        //JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE  防止中文被转义
        $result = $this->wx_post($url, json_encode($post_data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));

        $result = json_decode($result, true);
         print_r($result);die;
        // if (isset($result['prepay_id'])) {
        //     return $result['prepay_id'];
        // }
        return $result;
    }

    /**post请求
     * @param $url
     * @param $param
     * @return bool|string
     */
    private function wx_post($url, $param)
    {
        $authorization = $this->getV3Sign($url, "POST", $param);
        $curl = curl_init();
        $headers = [
            'Authorization:' . $authorization,
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
        curl_setopt($curl, CURLOPT_POST, true);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    /**
     * 微信提现V3签名
     * @param $url
     * @param $http_method
     * @param $body
     * @return string
     */
    private function getV3Sign($url, $http_method, $body)
    {
        $nonce = strtoupper($this->createNonceStr(32));
        $timestamp = time();
        $url_parts = parse_url($url);
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));

        $sslKeyPath = "./cert/apiclient_key.pem";
        $mchid='1676098779';


        $certPath='./cert/apiclient_cert.pem';
        $certContent = file_get_contents($certPath);
        $certData = openssl_x509_parse($certContent, true);
        $serial_n = $certData['serialNumberHex'];


        //拼接参数
        $message = $http_method . "\n" .
            $canonical_url . "\n" .
            $timestamp . "\n" .
            $nonce . "\n" .
            $body . "\n";
        $private_key = $this->getPrivateKey($sslKeyPath);
        openssl_sign($message, $raw_sign, $private_key, 'sha256WithRSAEncryption');
        $sign   = base64_encode($raw_sign);
        $token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%s",serial_no="%s",signature="%s"', $mchid, $nonce, $timestamp, $serial_n, $sign);
        return $token;
    }

    /**
     * 生成随机32位字符串
     * @param $length
     * @return string
     */
    public function createNonceStr($length = 16) { //生成随机16个字符的字符串
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 获取私钥
     * @param $filepath
     * @return false|resource
     */
    private function getPrivateKey($filepath = '')
    {

            $filepath = "./cert/apiclient_key.pem";

        return openssl_get_privatekey(file_get_contents($filepath));
    }





}
